<?php
namespace app\api\controller;
use app\api\controller\Common;
use app\api\model\Common as CommonModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\OrderGoods as OrderGoodsModel;
use think\Db;
use think\Log;

class Brokerage extends Common{

    public function moshi($order_num){

        $orders = Db::name('order')->where('id',$order_num)->find();
        $userId = $orders['user_id'];
        $member = Db::name('member')->where('id',$userId)->find();

        if ($orders['fenrun'] == 1){
            Log::info("订单已分润或分润失败:{$order_num}");
        }
        Log::info("执行订单模式:{$order_num}");
        // 启动事务
        Db::startTrans();
        try{
            //订单完成，确认收货了就开始计算佣金
            $aa = $this->commissionSettlement($orders,$member);
            //写入个人业绩
            $this->personalReward($userId,$orders['yuan_price']);
            //写入团队业绩
            if ($member['tuandui']){
                Db::name('tuandui')->where('id',$member['tuandui'])->setInc('money',$orders['yuan_price']);
            }
            //写入奖金池
            $this->jiangjinReward($userId,$orders['yuan_price']);

            //8购物消费（%）送积分(会员积分)
            $num1 = intval($orders['yuan_price']);
            $this->addIntegral($userId,$num1,8,$orders['id']);

            //会员购物增送30%的余额
            $money = intval($orders['yuan_price'] * 30 / 100);
            $this->insertWallet($userId,$money,1);

            Db::commit();
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::info("执行订单模式失败:{$e->getMessage()}");
        }
    }

    // 取消业绩奖励 付完款后尽量别取消 , 奖金池 团队业绩 个人业绩 积分全部都得变的
    public function quxiaoJiangli($orders){
        //取消业绩
        $member = Db::name('member')->where('id',$orders['user_id'])->find();
        Db::name('tuandui')->where('id',$member['tuandui'])->setDec('money',$orders['yuan_price']);
        $this->quxiaoReward($orders['user_id'],$orders['yuan_price']);
        $this->addIntegral($orders['user_id'],intval($orders['yuan_price']),18,$orders['id']);

        //取消奖励
        if ($orders['onefen_id']){
            Db::name('member')->where('id',$orders['onefen_id'])->setDec('yeji',$orders['yuan_price']);
            $this->decWallet($orders['onefen_id'],$orders['onefen_price'],4,$orders['id']);
        }
        if ($orders['twofen_id']){
            $this->decWallet($orders['twofen_id'],$orders['twofen_price'],4,$orders['id']);
        }

    }

    // 分销奖励 一级奖励15% 二级奖励5%
    public function commissionSettlement($orders,$member){
        // 寻找一级 二级
        $one_level = $member['one_level'];
        $two_level = $member['two_level'];
        //计算分润写入钱包
        $one_level_money =  $orders['yuan_price'] * 0.15;
        $two_level_money =  $orders['yuan_price'] * 0.05;
        $member_one = Db::name('member')->where('id',$one_level)->find();
        $member_two = Db::name('member')->where('id',$two_level)->find();


        if ($member_one && $member_one['vip'] == 1){
            $this->insertWallet($one_level,$one_level_money,11,$orders['id']);
        }else{
            $one_level_money = 0;
            $one_level = 0;
        }

        if ($member_two && $member_two['vip'] == 1){
            $this->insertWallet($two_level,$two_level_money,12,$orders['id']);
        }else{
            $two_level_money = 0;
            $two_level = 0;
        }
        $update = [
            'onefen_id' => $one_level,
            'twofen_id' => $two_level,
            'onefen_price' => $one_level_money,
            'twofen_price' => $two_level_money,
            'fenrun' => 1,
        ];
        Db::name('order')->where('id',$orders['id'])->update($update);

        Log::info("分销奖励完成{$one_level_money}/{$two_level_money}");

    }
    //钱包新增金额
    public function insertWallet($uid,$money,$sr_type,$oid=0){
        $wallet = Db::name('wallet')->where('user_id',$uid)->find();
        if($wallet){
            //增加金额
            Db::name('wallet')->where('user_id',$uid)->setInc("price",$money);
            $wid = $wallet['id'];
        }else{
            //增加钱包
            $wdata = [
                'price'  =>  $money,  'user_id'  => $uid
            ];
            $wid = db('wallet')->where('user_id',$uid)->insertGetId($wdata);
        }
        //增加明细
        $ddata = [
            'de_type'  => 1 , 'sr_type'  => $sr_type , 'zc_type' => 0 , 'price' => $money,'time' =>time(),
            'order_type' => 5 , 'order_id' => $oid, 'tx_id' => 0, 'wat_id' => $wid,'user_id'=>$uid
        ];
        db('detail')->insert($ddata);

    }
    //钱包扣减金额
    public function decWallet($uid,$money,$zc_type,$oid=0){
        $wallet = Db::name('wallet')->where('user_id',$uid)->find();
        if($wallet){
            //减少金额
            Db::name('wallet')->where('user_id',$uid)->setDec("price",$money);
            $wid = $wallet['id'];
        }
        //增加明细
        $ddata = [
            'de_type'  => 1 , 'sr_type'  => 0 , 'zc_type' => $zc_type , 'price' => $money,'time' =>time(),
            'order_type' => 5 , 'order_id' => $oid, 'tx_id' => 0, 'wat_id' => $wid,'user_id'=>$uid
        ];
        db('detail')->insert($ddata);

    }


    public function zhuanzhang($uid,$touid,$money)
    {
        $wallet = Db::name('wallet')->where('user_id',$uid)->value("price");
        $towallet = Db::name('wallet')->where('user_id',$touid)->value("price");

        if ($wallet >= $money){
            Db::startTrans();
            try{
                $this->decWallet($uid,$money,'5');
                $this->insertWallet($touid,$money,'13');
                // 提交事务
                Db::commit();
                return true;
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return lang('转账失败').$e->getMessage();
            }
        }else{
            return "用户余额不足";
        }
    }

    //写入个人业绩 付款直接写入 个人奖: 个人业绩达2w,200;5w,1000;10w,3000;50w,25000  每月月底奖励一次,不累计
    public function personalReward($uid,$money){
        //1. 更新上一级的业绩 只统计个人直推业绩
        $pMemberId = Db::name('member')->where('id',$uid)->value("pid");

        $member = Db::name('member')->where('id',$pMemberId)->field('yeji,yeji_tuan')->find();
        try {
            $update = [
                'yeji' => $money+$member['yeji'],
                'yeji_tuan' => $money+$member['yeji_tuan'],
            ];
            $res = Db::name('member')->where('id',$pMemberId)->update($update);

        }catch (\Exception $e) {
            Log::info("写入个人业绩失败:{$e->getMessage()}");
        }
    }


    // 计划执行个人业绩奖励 每月一次 2.如果个人业绩达标计算赠送金额更新余额并写入钱包记录　
    public function doPersonalReward(){
        $arr = [500000,100000,50000,20000];
        $arr2 = [25000,3000,1000,200];
        try {
            foreach ($arr as $k => $v){
                $uids = Db::name('member')->where('yeji','>=',$v)->column('id');
                foreach ($uids as $uid){
                    Db::name('member')->where('yeji','>=',$v)->update(['yeji'=>0]);
                    //写入余额
                    Db::name('wallet')->where('id',$uid)->setInc('price',$arr2[$k]);
                    $insert = [
                        'de_type'   =>1,
                        'sr_type'   =>8,
                        'price'     =>$arr2[$k],
                        'order_type'=>5,
                        'user_id'   =>$uid,
                        'time'      =>time()
                    ];
                    Db::name('detail')->insert($insert);
                }
            }
            Db::name('member')->update(['yeji'=>0]);
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::info("执行个人业绩奖励失败:{$e->getMessage()}");
        }
    }

    //计划执行 团队奖励 达200000每天奖励一次 团队成员享团队业绩5%的加权分红,按加权方式进行奖励,未执行的进入团队剩余
    public function doTuanduiReward()
    {
        $tuanduiList = Db::name('tuandui')->select();
        Db::startTrans();
        try {
            foreach ($tuanduiList as $tuandui){
                if ($tuandui['money'] >= 200000){
                    $userList = Db::name('member')
                        ->where('tuandui')->where('yeji','>',0)
                        ->field('id,yeji_tuan,yeji_tuan_yi')->select();
                    $wfh_tuan = $tuandui['money'] - $tuandui['money_yi'];
                    foreach ($userList as $user){
                        $wfh_yeji = $tuandui['yeji_tuan'] - $tuandui['yeji_tuan_yi'];
                        $money = $wfh_yeji/$wfh_tuan * 5/100;
                        if ($money >=0.1){
                            $insert = [
                                'de_type'   =>1,
                                'sr_type'   =>9,
                                'price'     =>$money,
                                'order_type'=>5,
                                'user_id'   =>$user['id'],
                                'time'      =>time()
                            ];
                            Db::name('detail')->insert($insert);
                            //写入余额
                            Db::name('wallet')->where('id',$user['id'])->setInc('price',$money);

                            Db::name('member')->where('id',$user['id'])->setInc('yeji_tuan_yi',$wfh_yeji);
                        }
                    }
                    // 计入已分红
                    Db::name('tuandui')->where('id',$tuandui['id'])->setInc('yeji_tuan_yi',$wfh_tuan);
                }
            }
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::info("执行团队奖励失败:{$e->getMessage()}");
        }
    }
    // 会员单赠送团队长管理奖励
    public function guanliJiang($price,$tuandui)
    {
        $money = $price * 5 /100;
        $tuandui = Db::name('tuandui')->where('id',$tuandui)->find();
        $uid = $tuandui['uid'];
        $this->insertWallet($uid,$money,10);
    }

    // 管理奖: 团队长享团队业绩5%提成奖励; 每天执行一次
    public function doGuanliReward(){
        $tuanduiList = Db::name('tuandui')->select();
        try {
            foreach ($tuanduiList as $tuandui){

                $wfh_guanli =  $tuandui['money'] - $tuandui['money_guanli'];
                $money = $wfh_guanli * 5/100;
                if ($money >= 0.1){
                    $insert = [
                        'de_type'   =>1,
                        'sr_type'   =>10,
                        'price'     =>$money,
                        'order_type'=>5,
                        'user_id'   =>$tuandui['uid'],
                        'time'      =>time()
                    ];
                    Db::name('detail')->insert($insert);
                    //写入余额
                    Db::name('wallet')->where('id',$tuandui['uid'])->setInc('price',$money);
                    Db::name('tuandui')->where('id',$tuandui['id'])->setInc('money_guanli',$wfh_guanli);
                }
            }
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::info("执行管理奖失败:{$e->getMessage()}");
        }
    }

    //奖金池 : 复购区5%销售额进入平台奖金池,从第二单开始算,注意加入到state 状态修改前
    public function jiangjinReward($uid,$money){
        $count = Db::name('order')->where('user_id',$uid)->where("state",1)->count();
        if ($count>1){
            $money = $money * 0.05;
            Db::name('jiangjinchi')->where('id',1)->setInc('value',$money);
        }
    }
    public function quxiaoReward($uid,$money){
        $count = Db::name('order')->where('user_id',$uid)->where("state",1)->count();
        if ($count>1){
            $money = $money * 0.05;
            Db::name('jiangjinchi')->where('id',1)->setDec('value',$money);
        }
    }
}